<?php

namespace App\Http\Controllers;

use App\Services\Bitrix24Service;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class BotController extends Controller
{
    protected $bitrix24;
    private $requestB24;

    public function __construct(Bitrix24Service $bitrix24)
    {
        $this->bitrix24 = $bitrix24;
    }

    public function handle(Request $request)
    {
        $this->requestB24 = $request;
        $event = $request->input('event');
        $auth = $request->input('auth');
        $params = $request->input('data.PARAMS');

        switch ($event) {
            case 'ONIMBOTMESSAGEADD':
                $this->handleMessageAdd($params);
                break;
            case 'ONIMBOTJOINCHAT':
                $this->handleJoinChat($params);
                break;
            case 'ONIMBOTDELETE':
                $this->handleBotDelete($auth['application_token']);
                break;
            case 'ONAPPINSTALL':
                $this->handleAppInstall();
                break;
        }

        return response()->json(['status' => 'OK']);
    }

    protected function isAuthorized($token)
    {
        $appsConfig = config('bitrix.apps');
        return isset($appsConfig[$token]);
    }

    protected function handleMessageAdd($params)
    {
        $message = $params['MESSAGE'];
        $userId = $params['FROM_USER_ID'];

        $report = $this->getAnswer($message, $userId);
        //$report['attach'][] = ["MESSAGE" => 'Как разберетесь с этими задачами, просто спросите еще раз [send=что горит]Что горит?[/send] и я дам новую сводку!'];

        $this->bitrix24->restCommand('imbot.message.add', [
            "DIALOG_ID" => $params['DIALOG_ID'],
            "MESSAGE" => $report['report'],
            //"ATTACH" => $report['attach']
        ], $this->requestB24->input('auth'));
    }

    protected function handleJoinChat($params)
    {
        $this->bitrix24->restCommand('imbot.message.add', [
            'DIALOG_ID' => $params['DIALOG_ID'],
            'MESSAGE' => 'Привет! Я IT помощник. Создам задачу или проконсультирую по любому вопросу. Какой у тебя вопрос?'
        ], $this->requestB24->input('auth'));
    }

    protected function handleBotDelete($token)
    {
        $appsConfig = config('bitrix.apps');
        unset($appsConfig[$token]);
        $this->saveConfig($appsConfig);
    }

    protected function handleAppInstall()
    {
        $handlerBackUrl = route('bot.handle');
        $result = $this->bitrix24->restCommand('imbot.register', [
            'CODE' => 'ITBotHelper',
            'TYPE' => 'B',
            'EVENT_MESSAGE_ADD' => $handlerBackUrl,
            'EVENT_WELCOME_MESSAGE' => $handlerBackUrl,
            'EVENT_BOT_DELETE' => $handlerBackUrl,
            'PROPERTIES' => [
                'NAME' => config('bitrix.bot_name'),
                'EMAIL' => config('bitrix.bot_email'),
                'PERSONAL_BIRTHDAY' => config('bitrix.bot_birthday'),
                'WORK_POSITION' => config('bitrix.bot_position'),
                'COLOR' => config('bitrix.bot_color'),
                'PERSONAL_GENDER' => config('bitrix.bot_gender')
            ]
        ], $this->requestB24->input('auth'));

        Log::info($result);

        $appsConfig = config('bitrix.apps');
        $appsConfig[$this->requestB24->input('auth.application_token')] = [
            'BOT_ID' => $result['result'],
            'LANGUAGE_ID' => $this->requestB24->input('data.LANGUAGE_ID')
        ];

        $this->saveConfig($appsConfig);
    }

    protected function saveConfig($apps)
    {
        $configPath = config_path('bitrix.php');

        // Получаем текущую конфигурацию
        $config = include $configPath;

        $config = array_merge($config, $apps);

        // Генерируем PHP-код для новой конфигурации
        $configContent = "<?php\n\nreturn " . var_export($config, true) . ";\n";

        // Записываем новый контент в конфигурационный файл
        file_put_contents($configPath, $configContent);
    }

    protected function getAnswer($command, $user)
    {
        // Используем сервис-контейнер для создания экземпляра AssistantController
        $assistantController = app()->make(AssistantController::class);

        $report = $assistantController->generateAssistantsResponse($command, $user);
        $report = $report->getOriginalContent();

        return [
            'report' => $report['assistant_response'] ?? "Произошла ошибка"
        ];
    }

    protected function getBadTasks($user)
    {
        $tasks = $this->bitrix24->restCommand('task.item.list', [
            'ORDER' => ['DEADLINE' => 'desc'],
            'FILTER' => ['RESPONSIBLE_ID' => $user, '<DEADLINE' => date("Y-m-d")]
        ]);

        if (count($tasks['result']) > 0) {
            $arTasks = array_map(function ($task) use ($user) {
                return [
                    'LINK' => [
                        'NAME' => $task['TITLE'],
                        'LINK' => "https://{$this->domain}/company/personal/user/{$user}/tasks/task/view/{$task['ID']}/"
                    ],
                    'DELIMITER' => [
                        'SIZE' => 400,
                        'COLOR' => '#c6c6c6'
                    ]
                ];
            }, $tasks['result']);

            return [
                'title' => 'Да, кое-какие задачи уже пролетели, например:',
                'report' => '',
                'attach' => $arTasks
            ];
        }

        return [
            'title' => 'Шикарно работаете!',
            'report' => 'Нечем даже огорчить - ни одной просроченной задачи'
        ];
    }
}
